package com.ruoyi.web.controller.sincerity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.SinDeed;
import com.ruoyi.system.service.ISinDeedService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SinSincerity;
import com.ruoyi.system.service.ISinSincerityService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 诚信事迹Controller
 *
 * @author buke
 * @date 2023-03-10
 */
@RestController
@RequestMapping("/system/sincerity")
public class SinSincerityController extends BaseController
{
    public static final String STUDENT = "学生" ;
    public static final String TEACHER = "教师" ;
    @Autowired
    private ISinSincerityService sinSincerityService;
    @Autowired
    private ISinDeedService deedService ;
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeptService deptService;

    /**
     * 查询诚信事迹列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SinSincerity sinSincerity)
    {
        List<SysUser> users = new ArrayList<>() ;

        List<SysRole> roles = SecurityUtils.getLoginUser().getUser().getRoles();
        for (SysRole role : roles) {
            if (StringUtils.isNotBlank(role.getRoleName())) {
                if (STUDENT.equals(role.getRoleName())){
                    sinSincerity.setMainUserId(SecurityUtils.getUserId());
                }else if (TEACHER.equals(role.getRoleName())){
                    if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())){
                        SysUser user = SecurityUtils.getLoginUser().getUser();
                        SysUser sysUser = new SysUser();
                        LambdaQueryWrapper<SysDept> wrapper = new LambdaQueryWrapper<>();
                        wrapper.eq(SysDept::getLeader,user.getNickName()) ;
                        List<SysDept> list = this.deptService.list(wrapper);
                        if (CollectionUtils.isNotEmpty(list)){
                            for (SysDept sysDept : list) {
                                sysUser.setDeptId(sysDept.getDeptId());
                                users.addAll(userService.selectUserList(sysUser)) ;
                            }
                        }
                    }
                    if (CollectionUtils.isNotEmpty(users)){
                        users = users.stream().distinct().collect(Collectors.toList()) ;
                    }
                }
            }
        }
        startPage();
        LambdaQueryWrapper<SinSincerity> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(sinSincerity.getTitle()),SinSincerity::getTitle,sinSincerity.getTitle());
        wrapper.like(StringUtils.isNotBlank(sinSincerity.getContent()),SinSincerity::getContent,sinSincerity.getContent());
        wrapper.eq(StringUtils.isNotBlank(sinSincerity.getSincerityType()),SinSincerity::getSincerityType,sinSincerity.getSincerityType()) ;
        wrapper.eq(StringUtils.isNotBlank(sinSincerity.getSincerityTypeName()),SinSincerity::getSincerityTypeName,sinSincerity.getSincerityTypeName()) ;
        wrapper.eq(!Objects.isNull(sinSincerity.getSincerityTypeId()),SinSincerity::getSincerityTypeId,sinSincerity.getSincerityTypeId()) ;
        wrapper.eq(!Objects.isNull(sinSincerity.getSincerityNumber()),SinSincerity::getSincerityNumber,sinSincerity.getSincerityNumber()) ;
        wrapper.eq(StringUtils.isNotBlank(sinSincerity.getMainUser()),SinSincerity::getMainUser,sinSincerity.getMainUser()) ;
        wrapper.eq(!Objects.isNull(sinSincerity.getMainUserId()),SinSincerity::getMainUserId,sinSincerity.getMainUserId()) ;

        /**老师权限*/
        wrapper.in(CollectionUtils.isNotEmpty(users),SinSincerity::getMainUserId, new ArrayList<>(users.stream().collect(Collectors.toMap(SysUser::getUserId, SysUser::getUserId)).keySet())) ;
        wrapper.orderByDesc(SinSincerity::getCreateTime) ;

        List<SinSincerity> list = sinSincerityService.list(wrapper);
        List<SinDeed> sinDeeds = deedService.selectSinDeedList(new SinDeed());
        Map<Long, SinDeed> map = sinDeeds.stream().collect(Collectors.toMap(SinDeed::getId, (s) -> (s)));

        Map<Long,String> collect = userService.list().stream().collect(Collectors.toMap(SysUser::getUserId, SysUser::getUserName));
        for (SinSincerity sincerity : list) {
            SinDeed sinDeed = map.get(sincerity.getSincerityTypeId());
            sincerity.setSincerityNumber(sinDeed.getScoreNumber());
            sincerity.setSincerityTypeName(sinDeed.getName());
            sincerity.setSincerityType(sinDeed.getType());
            
            sincerity.setUsername(collect.get(sincerity.getMainUserId()));
        }


        return getDataTable(list);
    }

    /**
     * 导出诚信事迹列表
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response, SinSincerity sinSincerity)
    {
        List<SinSincerity> list = sinSincerityService.selectSinSincerityList(sinSincerity);
        ExcelUtil<SinSincerity> util = new ExcelUtil<SinSincerity>(SinSincerity.class);
        util.exportExcel(response, list, "诚信事迹数据");
    }

    /**
     * 获取诚信事迹详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sinSincerityService.selectSinSincerityById(id));
    }

    /**
     * 新增诚信事迹
     */
    @PostMapping
    public AjaxResult add(@RequestBody SinSincerity sinSincerity)
    {
        return toAjax(sinSincerityService.insertSinSincerity(sinSincerity));
    }

    /**
     * 修改诚信事迹
     */
    @PutMapping
    public AjaxResult edit(@RequestBody SinSincerity sinSincerity)
    {
        return toAjax(sinSincerityService.updateSinSincerity(sinSincerity));
    }

    /**
     * 删除诚信事迹
     */
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sinSincerityService.deleteSinSincerityByIds(ids));
    }
}
